﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;

public partial class WebForm_ManageContact_AddContact : System.Web.UI.UserControl
{
    UploadFileDAO ufd = new UploadFileDAO();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddlFileType();   //將檔案類別加到下拉選單
        }

        string filePath = ufd.GetFilePath(ddlType.SelectedValue);
        BindGV1(filePath);
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        

        if (FileUpload1.HasFile)
        {
            int pathLength = ddlType.SelectedValue.Length;
            string fileSaveName = ufd.GetFileSaveName();
            string filePath = ufd.GetFilePath(ddlType.SelectedValue);
            string fileShortName = FileUpload1.FileName.Substring(0, FileUpload1.FileName.IndexOf('.'));
            string fileType = FileUpload1.FileName.Substring(FileUpload1.FileName.IndexOf('.'), FileUpload1.FileName.Length - FileUpload1.FileName.IndexOf('.'));

            //判斷檔案存放資料夾是否存在
            CheckFolder(HttpContext.Current.Request.MapPath("~/"), filePath.Substring(2));

            string[] filename = Directory.GetFiles(HttpContext.Current.Request.MapPath("~/") + filePath.Substring(2));

            //string path = HttpContext.Current.Request.MapPath("~/")            //取得網站根目錄,並設定檔案存放路徑及名稱
            //                    + filePath.Substring(2) + FileUpload1.FileName;
            //string path = Server.MapPath(MyObj.GetFilePath("OrganizationContactInfo", true));
            string path = Server.MapPath(MyObj.GetFilePath(this.ddlType.SelectedValue, true));

            GetFilePath(HttpContext.Current.Request.MapPath("~/"), filePath.Substring(2));            
                
            //將檔案資料存到資料庫
            //ufd.InsertData(ddlType.SelectedValue, "", FileUpload1.FileName, fileShortName,
            //                fileType, filePath, fileSaveName, "", clsAuth.GetUserID(), DateTime.Now.ToString());
 
            FileUpload1.SaveAs(path);

            Response.Write("<script language='javascript' type='text/javascript'>alert('上傳成功');</script>");

            BindGV1(filePath);
        }
        else
        {
            //Response.Write("<script language='javascript' type='text/javascript'>alert('請輸入檔案的路徑');</script>");           
        }
        
    }

    //將檔案類別加到下拉選單
    public void ddlFileType()
    {
        clsData dat = new clsData();
        MyStringBuilder sqlstr = new MyStringBuilder();
        DataTable dt = new DataTable();

        sqlstr.AppendFormat("select distinct FileGroupID,FilePath,Description,IsFile from [FileGroup] ");
        sqlstr.AppendFormat("where IsFile = '{0}' ", 'Y');
        //string sqlstr = "select distinct FileGroupID,FilePath,Description from FileGroup";

        dt = dat.GetData(sqlstr);

            for (int i = 0; i < dt.Rows.Count; ++i)
            {
                ListItem item = new ListItem();

                item.Value = dt.Rows[i]["FileGroupID"].ToString();
                item.Text = dt.Rows[i]["Description"].ToString();

                ddlType.Items.Add(item);
            }

            //this.ddlType.SelectedValue = "OrganizationContactInfo";

            this.ddlType.Enabled = true;
    }


    public void CheckFolder(String Path,String Folder)
    {
        string[] folderName = Folder.Split('\\');

        string s1 = folderName[0].ToString();
        string s2 = folderName[1].ToString();
        string s3 = folderName[2].ToString();

        if (!Directory.Exists(Path + folderName[0]))
        {
            Directory.CreateDirectory(Path + folderName[0]);
        }

        if (!Directory.Exists(Path + folderName[0] + folderName[1]))
        {
            Directory.CreateDirectory(Path + folderName[0] + "\\" + folderName[1]);
        }
        

        
    }

    public void BindGV()
    {
        DataTable dt = new DataTable();
        UploadFileDAO ufo = new UploadFileDAO();
        dt = ufo.GetFileData(ddlType.SelectedValue);
        
        gv.DataSource = dt;
        gv.DataBind();
    }

    public void BindGV1(String Path)
    {

        try
        {
            DataTable dt = new DataTable();
            DataColumn dc1 = new DataColumn();
            dc1.DataType = System.Type.GetType("System.String");
            dc1.ColumnName = "FileName";
            dt.Columns.Add(dc1);

            DataColumn dc2 = new DataColumn();
            dc2.DataType = System.Type.GetType("System.String");
            dc2.ColumnName = "FilePath";
            dt.Columns.Add(dc2);

            DataRow dr;

            String[] filepath = Directory.GetFiles(HttpContext.Current.Request.MapPath("~/") + Path.Substring(2));


            string sss = filepath[0].ToString();

            for (int i = 0; i < filepath.Length; ++i)
            {
                dr = dt.NewRow();
                string[] filename = filepath[i].Split('\\');
                dr["FileName"] = filename[filename.Length - 1];
                dr["FilePath"] = filepath[i];
                dt.Rows.Add(dr);
            }

            gv.DataSource = dt;
            gv.DataBind();
        }
        catch
        {
            DataTable dt = new DataTable();
            gv.DataSource = dt;
            gv.DataBind();
        }
    }

    public void GetFilePath(String Path, String Folder)
    {
        string[] file = Directory.GetFiles(Path + Folder);
        DataTable dt = new DataTable();
        UploadFileDAO ufo = new UploadFileDAO();
        dt = ufo.GetFileData(ddlType.SelectedValue);

        //Response.Write("<script language='javascript' type='text/javascript'>alert('" + file.Length.ToString() + "');</script>");

    }

    protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
    {
        string filePath = ufd.GetFilePath(ddlType.SelectedValue);
        BindGV1(filePath);
    }

    public void DownFile(String FileName)
    {
        string filename = FileName;

        FileInfo file = new FileInfo(filename);


        Response.Clear();
        Response.ContentType = "application/save-as";
        Response.Charset = "UTF-8";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.Name));
        Response.WriteFile(file.FullName);
        Response.End();
    }

    protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        DownFile(e.CommandArgument.ToString());   
    }
}
